package com.allenkerr.rpc.common;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * Rpc解码器
 * <p>
 * Created by 小柯(Allen Kerr) on 17.5.23 18:17.
 */
public class RpcDecoder extends ByteToMessageDecoder {

    private Class<?> genericClass;

    //由构造函数传入需要反序列化的class
    public RpcDecoder(Class<?> genericClass) {
        this.genericClass = genericClass;
    }


    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf inData, List<Object> out) throws Exception {
        if (inData.readableBytes() < 4)
            return;
        inData.markReaderIndex();
        int dataLength = inData.readInt();
        if (dataLength < 0)
            ctx.close();
        if (inData.readableBytes() < dataLength)
            inData.resetReaderIndex();
        //将 byteBuf 转换为 byte[]
        byte[] bytes = new byte[dataLength];
        inData.readBytes(bytes);
        //将 data 转换为 object
        Object object = RpcSerializationUtils.deserialize(bytes, genericClass);
        out.add(object);
    }
}
